local skill = fk.CreateSkill {
  name = "lvshi_poison_skill",
}

skill:addEffect("cardskill", {
  prompt = function(self, player, selected_cards)
    local card = Fk:cloneCard("lvshi_poison")
    card:addSubcards(selected_cards)
    local max_num = self:getMaxTargetNum(player, card)
    if max_num > 1 then
      local num = #table.filter(Fk:currentRoom().alive_players, function (p)
        return p ~= player and not player:isProhibited(p, card)
      end)
      max_num = math.min(num, max_num)
    end
    return max_num > 1 and "#lvshi_poison_multi:::" .. max_num or "#lvshi_poison_skill"
  end,
  target_num = 1,
  max_turn_use_time = 1,
  can_use = function(self, player, card, extra_data)
    if player:prohibitUse(card) then return end
    return (extra_data and extra_data.bypass_times) or
      table.find(Fk:currentRoom().alive_players, function(p)
        return self:withinTimesLimit(player, Player.HistoryTurn, card, "lvshi_poison", p)
      end)
  end,
  mod_target_filter = function(self, player, to_select, selected, card)
    return to_select ~= player and player:distanceTo(to_select) == 1
  end,
  target_filter = Util.CardTargetFilter,
  on_effect = function(self, room, effect)
    local n = 1
    effect.extra_data = effect.extra_data or {}
    n = n + (effect.extra_data.additionalPoison or 0)
    if not effect.to.dead then
      room:loseHp(effect.to, n, skill.name)
    end
  end,
})

skill:addEffect(fk.AfterCardsMove, {
  global = true,
  priority = 0.1,
  anim_type = "negative",
  can_trigger = function(self, event, target, player, data)
    local poison_losehp = (data.extra_data or {}).lvshi_poison_losehp or {}
    return table.contains(poison_losehp, player.id) and table.every(player.room.alive_players, function(p) return not p.dying end)
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local poison_losehp = (data.extra_data or {}).lvshi_poison_losehp or {}
    player.room:loseHp(player, #table.filter(poison_losehp, function(pid) return pid == player.id end), skill.name)
  end,

  can_refresh = function(self, event, target, player, data)
    for _, move in ipairs(data) do
      if move.toArea == Card.DiscardPile then
        return player.room.current and player.room.current == player
      end
    end
    return false
  end,
  on_refresh = function(self, event, target, player, data)
    for _, move in ipairs(data) do
      for _, info in ipairs(move.moveInfo) do
        if move.toArea == Card.DiscardPile then
          local id = info.cardId
          if Fk:getCardById(id).name == "lvshi_poison" then
            data.extra_data = data.extra_data or {}
            local poison_losehp = data.extra_data.lvshi_poison_losehp or {}
            table.insert(poison_losehp, player.id)
            data.extra_data.lvshi_poison_losehp = poison_losehp
          end
        end
      end
    end
  end,
})

return skill
